/**
 * 
 */
package com.gitee.adapter.proxy;

import org.springframework.context.ApplicationContext;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class RouteServiceProxy<T> implements InvocationHandler{
    private String serviceName;
    private ApplicationContext context;

    public RouteServiceProxy(String serviceName, ApplicationContext context) {
        this.serviceName = serviceName;
        this.context = context;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        String routeCode = null;
        Annotation[ /* 参数个数索引 */][ /* 注解个数索引 */ ] paramsAnno = method.getParameterAnnotations();
        if (paramsAnno != null) {
            for (int i = 0; i < paramsAnno.length; i++) {
                if (paramsAnno[i].length > 0) {
                    routeCode = (String) args[i]; // 获取到路由的参数值
                    break;
                }
            }
        }

        return method.invoke(context.getBean(genBeanName(routeCode, serviceName)),  args);
    }

    /**
     *
     * @param sellerCode 用于区分是哪个Service 编码
     * @param interfaceSimpleName 服务接口
     * @return
     */
    private String genBeanName(String sellerCode, String interfaceSimpleName) {
        return new StringBuilder(sellerCode.toLowerCase()).append(interfaceSimpleName).toString();
    }

}
